﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace zielonka.co.uk.extensions.system
{
    //Description:	Extracts all fields from a string that match a certain regex. Will convert to desired type through a standard TypeConverter.
    /*
        public static int[ ] ExtractInts( this string s )
        {
            return s.REExtract<int>( @"\d+" );
        }

        int[] a = "Some primes: 2, 5, 11, and 17".ExtractInts();
        // a == { 2, 5, 11, 17 }

    */

    public static partial class StringExtensions
    {
        public static T[] RegExExtract<T>(this string s, string regex)
        {
            TypeConverter tc = TypeDescriptor.GetConverter(typeof(T));
            if (!tc.CanConvertFrom(typeof(string)))
            {
                throw new ArgumentException("Type does not have a TypeConverter from string", "T");
            }
            if (!string.IsNullOrEmpty(s))
            {
                return
                    Regex.Matches(s, regex)
                    .Cast<Match>()
                    .Select(f => f.ToString())
                    .Select(f => (T)tc.ConvertFrom(f))
                    .ToArray();
            }
            
            return new T[0];
        }

    }
}
